package core.database;

import jade.util.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class StatementUpdate {
	
	private Logger log = Logger.getJADELogger(this.getClass().getName());
	
	private Connection dbCon;
	private String tableName;
	private boolean firstField;
	private boolean firstWhere;
	private String strSetFieldValues;
	private String strWhereFieldValues;
	private Statement st;
	
	public StatementUpdate (Connection dbCon) {
		this.dbCon = dbCon;
		this.tableName=null;
		firstField=true;
		firstWhere=true;
		st= null;
	
	}
	
	
	public void addSetFieldValue ( String field, String value){
		if (firstField){
			strSetFieldValues = " set "+field+"='"+value+"'";
			firstField = false;
		} else {
			strSetFieldValues = strSetFieldValues + ", "+field+"='"+value+"'";
		}
	}
	
	public void addSetFieldValue ( String field, long value){
		if (firstField){
			strSetFieldValues = " set "+field+"="+value+" ";
			firstField = false;
		} else {
			strSetFieldValues = strSetFieldValues + ", "+field+"="+value+" ";
		}
	}
	
	public void setTableName ( String tableName){
		this.tableName = tableName;
	}
	
	public void addWhereFieldValue ( String field, long value){
		if (firstWhere){
			strWhereFieldValues = " where "+field+"="+value+" ";
			firstWhere = false;
		} else {
			strWhereFieldValues = strWhereFieldValues + " and "+field+"="+value+" ";
		}
	}
	
	public boolean executeUpdate() throws SQLException{
		boolean update = false;
		if (tableName != null && strSetFieldValues != null) {
			String query = "update "+tableName+" "+strSetFieldValues + strWhereFieldValues;
			log.info("Execute query update:" + query);
			st = dbCon.createStatement();
			update =  st.execute(query);
		}
		return update;

	}
	
	public void close() throws SQLException{
		
		if (st != null) st.close();
	}
	
	
}
